<template>
  <div>
    <!-- 签名组件 -->
    <div style="margin: 20px auto">
      <vue-esign
        id="canvas"
        style="border: 1px solid #000"
        ref="esign"
        :width="800"
        :height="300"
        :isCrop="isCrop"
        :lineWidth="lineWidth"
        :lineColor="lineColor"
        :bgColor.sync="bgColor"
      />
    </div>
    <div>
      <button @click="handleReset">清空画板</button>
      <button @click="handleGenerate">生成图片</button>
      <button @click="downLoadImg">下载图片</button>
    </div>

    <div
      v-show="resultImg"
      style="
        border: 1px solid red;
        width: 400px;
        height: 200px;
        margin: 20px 100px;
        background: #ccc;
      "
    >
      <img
        :src="resultImg"
        alt=""
        style="display: inline-block; width: 100%; height: 100%"
      />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      lineWidth: 4,
      bgColor: "",
      lineColor: "red",
      resultImg: "",
      isCrop: false,
    };
  },
  methods: {

    handleReset() {
      console.log(this.$refs.esign);
      // 清除
      if (this.$refs.esign) {
        this.$refs.esign.reset();
        // var obj = document.getElementById("canvas");
        // obj.style.backgroundColor = "#ccc"; //保存时背景;
      }
      this.resultImg = "";
    },
    //生成签名图片..
    handleGenerate() {
      this.$refs.esign
        .generate()
        .then((res) => {
          this.resultImg = res;
        })
        .catch((e) => {
          this.$message.error("未签名");
        });
    },
    // 图片下载
    downLoadImg() {
      if (this.resultImg == "") {
        return this.$message.warning("未签名");
      }
      let randnum = Math.random() * 10000000000000;
      randnum = Math.floor(randnum);
      let fileName = "dianziqianming/" + randnum + ".png"; //文件名称
      let file = this.dataURLtoFile(this.resultImg, fileName); //转换成文件格式
      var aLink = document.createElement("a"); // 创建一个a标签
      var event = document.createEvent("HTMLEvents"); //创建事件
      event.initEvent("click", true, true);
      aLink.download = fileName; // 使用时间戳给文件命名
      aLink.href = URL.createObjectURL(file); //传入文件
      aLink.click();
    },
    //将base64转换为文件..
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
};
</script>

<style>
</style>